package com.yunkaweilai.android.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yunkaweilai.android.R;
import com.yunkaweilai.android.model.LockQRBean;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.utils.zxing.Kutils;
import com.yunkaweilai.android.view.MyToast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;

/**
 * 下载会员激活图片dialog
 */

public class LockPicDownloadDialog extends Dialog {

    private RelativeLayout bgline;
    private LinearLayout downline;
    private LinearLayout allline;
    private ImageView imgHead;
    private ImageView imgQR;
    private ImageView imgClose;
    private ImageView imgbg;
    private TextView idTvName;
    private TextView idTvPhone;
    private TextView idTvLevel;
    private TextView idTvMoney;
    private LockQRBean model;
    private Context context;

    public LockPicDownloadDialog(Context context, LockQRBean model) {
        super(context, R.style.dialog);
        this.context = context;
        this.model = model;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_lock_pic);
        initView();
        initdate();
    }


    private void initView() {
        bgline = findViewById(R.id.bg_line);
        allline = findViewById(R.id.line_all);
        downline = findViewById(R.id.id_img_close);
        imgHead = findViewById(R.id.id_img_touxiang);
        imgQR = findViewById(R.id.img_qr);
        imgbg = findViewById(R.id.img_bg);
        imgClose = findViewById(R.id.img_close);
        idTvName = findViewById(R.id.bitmap_name);
        idTvPhone = findViewById(R.id.bitmap_phone);
        idTvLevel = findViewById(R.id.bitmap_level);
        idTvMoney = findViewById(R.id.bitmap_money);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initdate() {
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        if (!Utils.isEmpty(model.getData().getInfo().getShare_img())) {
//            imgbg.setImageBitmap(Kutils.stringToBitmap(model.getData().getInfo().getShare_img()));
            GlideUtils.loadImage(context, model.getData().getInfo().getShare_img(), imgbg);
        } else {
//            bgline.setBackground(new BitmapDrawable(context.getResources().getString(R.string.img_64_lock)));
        }
        Utils.MemberHeadImg(context, model.getData().getInfo().getMember_avatar(), model.getData().getInfo().getMember_sex(), imgHead);
        idTvName.setText(model.getData().getInfo().getMember_name());
        idTvPhone.setText("手机：" + model.getData().getInfo().getMember_tel());
        idTvLevel.setText("等级：" + model.getData().getInfo().getLevel_name());
        idTvMoney.setText("费用：" + model.getData().getInfo().getLock_price());
        imgQR.setImageBitmap(Kutils.stringToBitmap(model.getData().getUnlock_qr()));
        downline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewSaveToImage(bgline);
                MyToast.showShortToast(context, "图片保存成功");
                dismiss();

            }
        });
    }


    private void viewSaveToImage(View view) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        FileOutputStream fos;
        String imagePath = "";
        try {
            // 判断手机设备是否有SD卡
            boolean isHasSDCard = Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED);
            if (isHasSDCard) {
                // SD卡根目录
                File sdRoot = Environment.getExternalStorageDirectory();
                File file = new File(sdRoot, model.getData().getInfo().getMember_name() + Calendar.getInstance().getTimeInMillis() + ".png");
                fos = new FileOutputStream(file);
                imagePath = file.getAbsolutePath();
                updatePhotoMedia(file, context);
            } else
                throw new Exception("创建文件失败!");

            cachebmp.compress(Bitmap.CompressFormat.PNG, 100, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        view.destroyDrawingCache();
    }


    //更新图库
    private static void updatePhotoMedia(File file, Context context) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        context.sendBroadcast(intent);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);

        return bmp;
    }

//
//    private void saveBitmap(Bitmap bitmap) {
//        FileOutputStream fos;
//        try {
//            File root = Environment.getExternalStorageDirectory();
//            File file = new File(root, model.getData().getInfo().getMember_name() + Calendar.getInstance() + ".png");
//            fos = new FileOutputStream(file);
//            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
//            fos.flush();
//            fos.close();
//            MediaScannerConnection.scanFile(context, new String[]{file.toString()}, null, null);
//            MyToast.showShortToast(context,"保存成功");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * @param linearLayout 要转化为图片的布局
//     */
//    private Bitmap generatBitmap(LinearLayout linearLayout) {
//        linearLayout.setDrawingCacheEnabled(true);
//        linearLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        linearLayout.layout(0, 0, linearLayout.getMeasuredWidth(), linearLayout.getMeasuredHeight());
//        linearLayout.buildDrawingCache();
//        Bitmap bitmap = Bitmap.createBitmap(linearLayout.getDrawingCache());
//        linearLayout.setDrawingCacheEnabled(false);
//        linearLayout.setGravity(Gravity.CENTER);  //因为刚刚重新测量布局一次，需要重新设置view居中\
//        return bitmap;
//    }
//
//    private Bitmap createBitmap(View view) {
//        view.buildDrawingCache();
//        Bitmap bitmap = view.getDrawingCache();
//        return bitmap;
//    }
//
//    public Bitmap createBitmap2(View v) {
//        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
//        Canvas c = new Canvas(bmp);
//        c.drawColor(Color.WHITE);
//        v.draw(c);
//        return bmp;
//    }
//
//    public Bitmap createBitmap3(View v, int width, int height) {
//        //测量使得view指定大小
//        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
//        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
//        v.measure(measuredWidth, measuredHeight);
//        //调用layout方法布局后，可以得到view的尺寸大小
//        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
//        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
//        Canvas c = new Canvas(bmp);
//        c.drawColor(Color.WHITE);
//        v.draw(c);
//        return bmp;
//    }
}
